from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
import openpyxl
import datetime
# 等待整个table加载完成，否则因网络延迟，driver.page_source可能会拿不到数据
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

# wb = openpyxl.load_workbook(r"D:\tiktok.xlsx")
wb = openpyxl.Workbook()
ws = wb.create_sheet('自定义订单模板')
# sheet = wb.worksheets[0]
list1 = ['1']
list2 = ['1']
list3 = ['1']
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('--ignore-certificate-errors')
rizhi = chrome_options.add_argument('--log-level=3')
browser = webdriver.Chrome(options=chrome_options,executable_path=r'C:\Program Files\Google\Chrome\Application\chromedriver.exe')
# ,executable_path=r'C:\Program Files\Google\Chrome\Application\chromedriver.exe'

def oop3():
    # browser = webdriver.Chrome()
    browser.get('https://seller.tiktokglobalshop.com/account/login')
    browser.maximize_window()
    time.sleep(3)
    WebDriverWait(browser, 60).until(EC.presence_of_element_located((By.ID, 'TikTok_Ads_SSO_Login_Form')))
    browser.find_element_by_xpath(
        "//div[@id='TikTok_Ads_SSO_Login_Form']/div[@id='TikTok_Ads_SSO_Login_Form_Content']/div[@id='TikTok_Ads_SSO_Login_Mobile_FormItem']/span[@id='TikTok_Ads_SSO_Login_Email_Panel_Button']").click()
    time.sleep(3)
    #
    # # 输入账户密码
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Email_Input').click()
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Email_Input').send_keys('xiaoyueteng@outlook.com')
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Pwd_Input').click()
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Pwd_Input').send_keys('6Q?4g#a1')
    time.sleep(2)
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Btn').send_keys(Keys.ENTER)

    time.sleep(6)

    browser.get('https://seller.tiktokglobalshop.com/order?subTab=awaiting_collection&tab=to_ship')
    time.sleep(6)
    print("再次刷新！！！！！！")

    browser.get('https://seller.tiktokglobalshop.com/order?subTab=awaiting_collection&tab=to_ship')
    time.sleep(6)
    # page1=browser.find_elements_by_xpath("//div[@class='arco-spin i18n-ecom-spin']/div[@class='arco-spin-children']/div[@class='zep-pagination justify-end']/ul[@class='zep-pagination-list']")
    # for i in page1:
    #     print(i)
    #     print(i.text)
    num=0
    while 1:
        num+=1
        print(f'第{num}页数据获取中！！！！！！！')
        WebDriverWait(browser, 120).until(
            EC.presence_of_element_located((By.CLASS_NAME, 'index__TBodyContainer--ScorV')))
        one_all = browser.find_elements_by_xpath(
            "//tbody[@class='index__TBodyContainer--ScorV']/tr[@class='index__TBodyRowHeader--1St6W']")
        two_all = browser.find_elements_by_xpath(
            "//div[@class='index__content--2rT_g font-regular text-base text-gray-1 break-all']")
        for one_i in range(len(one_all)):
            allstr=one_all[one_i].text.split('\n')
            # print(two_all[one_i].text)
            # print(one_all[one_i].text[:18])  # 获取576460906570287455，24/10/2021 13:04:08
            # print(one_all[one_i].text[-19:])
            # print(one_all[one_i].text)
            # print("*"*20)
            # time1 = one_all[one_i].text[-19:]
            # name1 = one_all[one_i].text[19:-19]
            # number1 = one_all[one_i].text[:18]
            time1 = allstr[2]
            name1 = allstr[1]
            number1 = allstr[0]
            list1.append(time1)
            list2.append(number1)
            list3.append(name1)

        try:
            browser.find_element_by_xpath(
                "//div[@class='arco-spin i18n-ecom-spin']/div[@class='arco-spin-children']/div[@class='zep-pagination justify-end']/ul[@class='zep-pagination-list']/li[@class='zep-pagination-item zep-pagination-item-next']").click()
            time.sleep(6)
        except Exception as g:
            print('*'*20,f'总共有{len(list2)-1}单','*'*20)
            break

    oop4()

# 订单分类	参考号	币种	买家ID	仓库id	仓库运输方式	跟踪号	平台运输方式代码	付款时间	运费	平台手续费	paypal 交易号	销售sku	单价	数量	收件人名称	国家二字码	州或省	城市名称	地址第一行	电话
def oop4():
    today = str(datetime.date.today()).replace('-','/')
    today1 = datetime.date.today()
    oneday = datetime.timedelta(days=1)
    yesterday = str(today1 - oneday).replace('-', '/')
    ws.cell(1, 1).value = f"订单分类"  # 第1行第1列
    ws.cell(1, 2).value = f"参考号"  # 第1行第2列
    ws.cell(1, 3).value = f"币种"  # 第1行第3列
    ws.cell(1, 4).value = f"买家ID"  # 第1行第4列
    ws.cell(1, 5).value = f"仓库id"  # 第1行第5列
    ws.cell(1, 6).value = f"仓库运输方式"  # 第1行第6列
    ws.cell(1, 7).value = f"跟踪号"  # 第1行第7列
    ws.cell(1, 8).value = f"平台运输方式代码"  # 第1行第8列
    ws.cell(1, 9).value = f"付款时间"  # 第1行第9列
    ws.cell(1, 10).value = f"运费"  # 第1行第10列
    ws.cell(1, 11).value = f"平台手续费"  # 第1行第11列
    ws.cell(1, 12).value = f"paypal交易号"  # 第1行第12列
    ws.cell(1, 13).value = f"销售sku"  # 第1行第13列
    ws.cell(1, 14).value = f"单价"  # 第1行第14列
    ws.cell(1, 15).value = f"数量"  # 第1行第15列
    ws.cell(1, 16).value = f"收件人名称"  # 第1行第16列
    ws.cell(1, 17).value = f"国家二字码"  # 第1行第17列
    ws.cell(1, 18).value = f"州或省"  # 第1行第18列
    ws.cell(1, 19).value = f"城市名称"  # 第1行第19列
    ws.cell(1, 20).value = f"地址第一行"  # 第1行第20列
    ws.cell(1, 21).value = f"电话"  # 第1行第21列
    for i in range(1,len(list1)):
        number11 = list2[i]
        time11 = list1[i].split(' ')[0].split('/')
        time22=time11[2]+'/'+time11[1]+'/'+time11[0]
        name11 = list3[i]
        try:
            if time22 not in [today,yesterday]:
                break
            else:
                linshi(i, name11, number11, time22)
        except Exception as g:
            time.sleep(60)
            if time22 not in [today, yesterday]:
                break
            else:
                linshi(i, name11, number11, time22)
    print('程序执行完毕！！！')
    browser.close()
    filename = r"D:\tiktok.xlsx"
    wbs = openpyxl.load_workbook(filename)  # 加载表格
    wbs.save(r"D:\tiktok.xlsx")
    sh_name = wbs.worksheets  # 获取所有sheet
    wbs.remove_sheet(sh_name[0])
    wbs.save(r"D:\tiktok.xlsx")



def linshi(i,name11,number11,time22):
    browser.get(f'https://seller.tiktokglobalshop.com/order/detail?order_no={number11}')
    time.sleep(6)
    # index__sku-id--3OdTf xh-highlight
    WebDriverWait(browser, 120).until(EC.presence_of_element_located((By.CLASS_NAME, 'index__info--2ZlBl')))
    SellerSKU = browser.find_element_by_xpath(
        "//div[@class='index__info--2ZlBl']/div[@class='index__sku-id--3OdTf']").text
    num2 = browser.find_element_by_xpath(
        "//div[@class='index__container--3SeqM']/div[@class='index__content--PpRp3 bg-white']/div[@class='index__price--3KYvw']").text
    try:
        addr = browser.find_element_by_xpath(
            "//div[@class='index__leftContainer--3TLdq space-y-16']/div[@class='index__container--30FGM'][5]/div[@class='index__value--vChAg']").text
    except Exception as g:
        print('addr有问题，重复获取')
        time.sleep(10)
        addr = browser.find_element_by_xpath(
            "//div[@class='index__leftContainer--3TLdq space-y-16']/div[@class='index__container--30FGM'][4]/div[@class='index__value--vChAg']").text
        if len(addr)==1:
            addr = browser.find_element_by_xpath(
                "//div[@class='index__leftContainer--3TLdq space-y-16']/div[@class='index__container--30FGM'][5]/div[@class='index__value--vChAg']").text

    num22 = num2.split(' ')
    num2_moneylei = num22[0]
    num2_number = num22[3]
    num2_money = num22[1]
    wuliu1 = browser.find_element_by_xpath(
        "//div[@class='index__card--3DoQW rounded']/div[4]/div[@class='index__priceKeyValue--Fc6U2 mb-12 flex justify-between'][3]/div[@class='font-regular text-base text-gray-2'][2]").text
    wuliu2 = wuliu1.split(' ')[1]
    # print(f'第{i+1}个',number11,name11,time11,SellerSKU, num2, addr)
    ws.cell(i + 1, 1).value = f"线下订单"  # 第i + 1行第1列
    ws.cell(i + 1, 2).value = f"{number11}"  # 第i + 1行第2列
    ws.cell(i + 1, 3).value = f"{num2_moneylei}"  # 第i + 1行第2列
    ws.cell(i + 1, 4).value = f"{name11}"  # 第i + 1行第3列
    ws.cell(i + 1, 5).value = f"SW02"  # 第i + 1行第4列
    ws.cell(i + 1, 6).value = f"SHANGF"  # 第i + 1行第5列
    ws.cell(i + 1, 7).value = f"{addr}"  # 第i + 1行第3列
    ws.cell(i + 1, 8).value = f"TikTok Global Shipping"  # 第i + 1行第4列
    ws.cell(i + 1, 9).value = f"{time22}"  # 第i + 1行第5列
    ws.cell(i + 1, 10).value = f"{wuliu2}"  # 第i + 1行第1列
    ws.cell(i + 1, 11).value = f"0"  # 第i + 1行第2列
    ws.cell(i + 1, 12).value = f"{number11}"  # 第i + 1行第2列
    ws.cell(i + 1, 13).value = f"{SellerSKU.replace('Seller SKU : ', '')}"  # 第i + 1行第3列
    ws.cell(i + 1, 14).value = f"{num2_money}"  # 第i + 1行第4列
    ws.cell(i + 1, 15).value = f"{num2_number}"  # 第i + 1行第5列
    ws.cell(i + 1, 16).value = f"万色快递"  # 第i + 1行第3列
    ws.cell(i + 1, 17).value = f"CN"  # 第i + 1行第4列
    ws.cell(i + 1, 18).value = f"广东省"  # 第i + 1行第5列
    ws.cell(i + 1, 19).value = f"东莞市"  # 第i + 1行第3列
    ws.cell(i + 1, 20).value = f"碧湖大道16号安和创新科技园2栋13F"  # 第2行第4列
    ws.cell(i + 1, 21).value = f"17520458924"  # 第2行第5列
    print(f'第{i}个', 'line', number11, num2_moneylei, name11, 'SW02', 'SHANGF', addr, 'TikTok Global Shipping', time22,
          wuliu2, '0', number11, SellerSKU, num2_money, num2_number, "万色快递", "CN", "广东省", "东莞市", "碧湖大道16号安和创新科技园2栋13F",
          "17520458924")
    wb.save(r"D:\tiktok.xlsx")

    browser.back()
    time.sleep(6)



if __name__ == '__main__':
    oop3()
#     oop4()


# while True:
    #     newtime = time.strftime("%H:%M:%S", time.localtime())
    #     if newtime in ['08:30:00']:
    #         run()
    #         print('任务执行已完成')

